package calendar;

import edu.gmu.middleware.Message;
import edu.gmu.streams.BlockInputStream;
import edu.gmu.streams.BlockOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

/**
 * This class represents a single user
 */
public class User implements Message
{
    private int id;
    private String name;
    private int port;

    public User( )
    {
        this(0, "", 0);
    }
    
    public User( int id, String name )
    {
        this(id, name, 0);
    }
    
    public User( int id, String name, int port )
    {
        this.id   = id;
        this.name = name;
        this.port = port;
    }

    /**
     * Factory method to create a new user with a unique id.  Note that this
     * will not work with hash-lookup mechanism.
     * @param name
     * @param users (used to ensure no duplicate is created)
     * @return
     */
    public static User makeUser( String name, ArrayList users )
    {
        boolean unique = false;
        int temp = 0;

        while( !unique )
        {
            unique = true;
            Random r = new Random();
            temp = r.nextInt(65536); // returns value between 0 - 65535
            Iterator itr = users.iterator();
            while ( itr.hasNext() )
            {
                User u = (User)itr.next();
                if ( u.getId() == temp ) unique = false;
            }
        }
        return new User( temp, name );
    }

    public int getId()
    {
        return this.id;
    }

    public String getName()
    {
        return new String ( this.name );
    }

    public void setName( String name )
    {
        this.name = new String( name );
    }

    public int getPort()
    {
        return this.port;
    }

    public void setPort( int port )
    {
        this.port = port;
    }
    
    /**
     * Determines if this user is equal to another user
     * @param stream
     * @throws java.io.IOException
     */
    public boolean equals( Object obj )
    {
        if( obj == this ) return true;
        
        if( !(obj instanceof User) ) return false;
        User o = (User)obj;
        
        // Only check id - small chance id's are different and names equal
        return this.id == o.id;
    }

    public void marshal(BlockOutputStream stream) throws IOException
    {
        stream.writeInt( id );
        stream.writeUTF( name );
        stream.writeInt( port );
    }
    public void unmarshal(BlockInputStream stream) throws IOException
    {
        this.id   = stream.readInt();
        this.name = stream.readUTF();
        this.port = stream.readInt();
    }

    public String toString()
    {
    return ""+this.id;
    }
}
